package cn.jwcat.controller;

import cn.jwcat.dealEntity.DealUser;
import cn.jwcat.dealEntity.UserDto;
import cn.jwcat.entity.File;
import cn.jwcat.entity.Password;
import cn.jwcat.entity.Staff;
import cn.jwcat.entity.User;
import cn.jwcat.service.IFileService;
import cn.jwcat.service.IUserService;
import cn.jwcat.utils.JwtTokenUtil;
import cn.jwcat.utils.MD5;
import cn.jwcat.utils.result.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * 患者操作
 */
@RestController
@Transactional
@RequestMapping("/user")
public class UserController {
	@Resource
	IUserService userService;

	@Resource
	JwtTokenUtil jwtTokenUtil;

	@Resource
	IFileService fileService;

	@GetMapping("/{page}/{size}")
	@ApiOperation("获取患者列表")
	public Result getUserInfoList(HttpServletRequest request, @PathVariable("page") int page, @PathVariable("size") int size) {
		Staff staff = jwtTokenUtil.getStaffFromRequest(request);
		PageHelper.startPage(page, size);
		List<UserDto> users = userService.getUserInfoList(staff.getStaffId());
		for (UserDto user : users) {
			user.setPassword(null);
		}
		PageInfo<UserDto> userPageInfo = new PageInfo<>(users);
		return Result.success(userPageInfo);
	}

	@PostMapping("/query/{page}/{size}")
	@ApiOperation("模糊查询患者列表")
	public Result queryUser(HttpServletRequest request, @PathVariable("page") int page, @PathVariable("size") int size, @RequestBody User userVal) {
		Staff staff = jwtTokenUtil.getStaffFromRequest(request);
		PageHelper.startPage(page, size);
		List<UserDto> users = userService.queryUser(staff.getStaffId(), userVal.getUname());
		for (UserDto user : users) {
			user.setPassword(null);
		}
		PageInfo<UserDto> userPageInfo = new PageInfo<>(users);
		return Result.success(userPageInfo);
	}

	@DeleteMapping("/{userId}")
	@ApiOperation("根据id删除患者")
	public Result deleteUserById(HttpServletRequest request, @PathVariable Integer userId) {
		Staff staff = jwtTokenUtil.getStaffFromRequest(request);
		boolean delete = userService.deleteUserById(userId, staff.getStaffId());
		System.out.println(delete);
		if (delete) return Result.success("数据删除成功");
		return Result.error().message("请联系管理员，该患者的房间未找到");
	}

	@GetMapping("/{userId}")
	@ApiOperation("根据id获取患者详情")
	public Result getById(@PathVariable Integer userId) {
		User user = userService.getById(userId);
		return Result.success(user);
	}

	@PutMapping
	@ApiOperation("添加患者信息")
	public Result updateUser(@RequestBody User user) {
		return userService.updateUser(user);
	}

	@PostMapping
	@ApiOperation("更新患者信息")
	public Result postUser(@RequestBody User user) {
		return userService.postUser(user);
	}

	@GetMapping
	@ApiOperation("获取用户简单信息")
	public Result getUserInfo(HttpServletRequest request) {
		User info = jwtTokenUtil.getUserInfo(request);
		DealUser dealUser = new DealUser();
		dealUser.setUserId(info.getUserId());
		dealUser.setUname(info.getUname());
		dealUser.setPicture(info.getPicture());
		return Result.success(dealUser);
	}

	@GetMapping("phone")
	@ApiOperation("获取用户")
	public Result getUserInfoOnPhone(HttpServletRequest request) {
		Integer id = jwtTokenUtil.getIDFromRequest(request);
		return getById(id);
	}

	@PostMapping("/age")
	@ApiOperation("用户修改年龄")
	public Result changeAge(@RequestBody User user) {
		LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
		wrapper
			.set(User::getAge, user.getAge())
			.eq(User::getUserId, user.getUserId());
		boolean update = userService.update(wrapper);
		if (update) return Result.success("修改成功");
		return Result.error().message("年龄信息修改失败");
	}

	@PostMapping("/add")
	@ApiOperation("用户修改居住地址")
	public Result changeAdd(@RequestBody User user) {
		LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
		wrapper
			.set(User::getAddress, user.getAddress())
			.eq(User::getUserId, user.getUserId());
		boolean update = userService.update(wrapper);
		if (update) return Result.success("修改成功");
		return Result.error().message("地址信息修改失败");
	}

	@PostMapping("/tel")
	@ApiOperation("用户修改电话号码")
	public Result changeTel(@RequestBody User user) {
		LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
		wrapper
			.set(User::getTelephone, user.getTelephone())
			.eq(User::getUserId, user.getUserId());
		boolean update = userService.update(wrapper);
		if (update) return Result.success("修改成功");
		return Result.error().message("电话号码修改失败");
	}

	@PostMapping("/upload")
	@ApiOperation("用户图片文件上传")
	public Result uploadPic(HttpServletRequest request, MultipartFile file) throws IOException {
		User user = jwtTokenUtil.getUserInfo(request);
		// TODO: 2023-4-11 文件上传异常
		File uploadFile = fileService.upload(file);
		LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper
			.set(User::getPicture, uploadFile.getVirtualPath())
			.eq(User::getUserId, user.getUserId());
		boolean bool = userService.update(updateWrapper);
		if (!bool) return Result.error().message("图像修改失败");
		HashMap<String, String> map = new HashMap<>();
		map.put("picture", uploadFile.getVirtualPath());
		return Result.success(map);
	}

	@PutMapping("/pwd")
	@ApiOperation("修改密码")
	public Result changePwd(@RequestBody Password password) throws Exception {
		System.out.println(password);
		return userService.changePwd(password);
	}

	@PostMapping("/register")
	@ApiOperation("患者注册")
	public Result register(@RequestBody User user) throws Exception {
		LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
		wrapper
			.eq(User::getTelephone, user.getTelephone());
		List<User> list = userService.list(wrapper);
		System.out.println(list);
		if (list.size() != 0) return Result.error().message("该电话号码已注册。");
		LambdaQueryWrapper<User> newWrapper = new LambdaQueryWrapper<>();
		newWrapper
			.eq(User::getUname, user.getUname());
		List<User> newList = userService.list(newWrapper);
		if (newList.size() != 0) return Result.error().message("姓名已注册");
		user.setEnterTime(LocalDateTime.now());
		user.setPassword(MD5.md5MinusSalt(user.getPassword()));
		userService.save(user);
		return Result.success().message("注册成功").data(user.getUserId());
	}

	//	supplement
	@PostMapping("/supplement")
	@ApiOperation("患者补充信息")
	public Result supplement(@RequestBody User user) {
		Boolean select = userService.supplement(user.getRoomId(), user.getUserId());
		if (!select) return Result.error().message(user.getRoomId() + "号房间已有人居住，检查输入内容");
		LambdaUpdateWrapper<User> wrapper
			= new LambdaUpdateWrapper<>();
		wrapper.set(User::getAge, user.getAge()).set(User::getPicture, user.getPicture())
			.set(User::getIdCard, user.getIdCard()).set(User::getAddress, user.getAddress())
			.set(User::getRoomId, user.getRoomId()).eq(User::getUserId, user.getUserId());
		boolean update = userService.update(wrapper);
		if (update) return Result.success("填充完毕");
		return Result.error().message("填充失败");
	}
}
